import collections


class Solution(object):
    def findMinHeightTrees(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        if n == 1:
            return [0]
        if n == 2:
            return [0, 1]
        d = collections.defaultdict(int)
        c = collections.defaultdict(set)
        for edge in edges:
            d[edge[0]] += 1
            d[edge[1]] += 1
            c[edge[0]].add(edge[1])
            c[edge[1]].add(edge[0])
        now = set()
        left = {i for i in range(n)}
        for id in d:
            if d[id] == 1:
                now.add(id)
        left -= now
        while now and left:
            next_set = set()
            for id in now:
                for next_id in c[id]:
                    d[next_id] -= 1
                    c[next_id].remove(id)
                    if d[next_id] == 1:
                        next_set.add(next_id)
                    if d[next_id] == 0:
                        return [next_id]
            now = next_set
            left -= now
        return list(now)


data = Solution()
n = 4
edges = [[1, 0], [1, 2], [1, 3]]
print(data.findMinHeightTrees(n, edges))
n = 6
edges = [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]
print(data.findMinHeightTrees(n, edges))
